﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using CK.Project.Web.EntityFramework.Core;

namespace CK.Project.Web.WebAPI.App_Start
{
    /// <summary>
    /// 依赖注入配置类
    /// </summary>
    public class AutofacConfig
    {
        public static void CoreAutoFacInit()
        {
            var builder = new ContainerBuilder();
            HttpConfiguration config = GlobalConfiguration.Configuration;

            SetupResolveRules(builder);

            ////注册所有的Controllers
            //builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            //注册所有的ApiControllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();


            var container = builder.Build();
            //注册api容器需要使用HttpConfiguration对象
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        private static void SetupResolveRules(ContainerBuilder builder)
        {
            builder.RegisterGeneric(typeof(PgRepository<>)).As(typeof(PgRepository<>));
            //builder.RegisterGeneric(typeof(SysRepository<>)).As(typeof(IRepository<>));
            //WebAPI只用引用services和repository的接口，不用引用实现的dll。
            //如需加载实现的程序集，将dll拷贝到bin目录下即可，不用引用dll

            // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组  
            string[] fileList = System.IO.Directory.GetFileSystemEntries(System.AppDomain.CurrentDomain.BaseDirectory + "/bin");
            // 遍历所有的文件和目录  
            foreach (string file in fileList)
            {
                var _file = file.Substring(file.LastIndexOf("\\") + 1);
                if ((_file.ToUpper().IndexOf("CK.Project.Web") == 0 || _file.ToUpper().IndexOf("CK.PROJECT.WEB") == 0) && _file.ToUpper().EndsWith(".DLL"))
                {
                    var Application = Assembly.Load(_file.ToUpper().Replace(".DLL", ""));
                    builder.RegisterAssemblyTypes(Application, Application)
                      .Where(t => t.Name.EndsWith("AppService"))
                      .AsImplementedInterfaces();
                    //builder.RegisterAssemblyTypes(Application, Application)
                    //  .Where(t => t.Name.EndsWith("WFMethods"))
                    //  .AsImplementedInterfaces();
                    //builder.RegisterAssemblyTypes(Application, Application)
                    //  .Where(t => t.Name.EndsWith("Helper"))
                    //  .AsImplementedInterfaces();
                    //builder.RegisterAssemblyTypes(Application, Application)
                    //      .Where(t => t.Name.EndsWith("Handler"))
                    //      .AsImplementedInterfaces();
                    //Type handlerType = Application.GetTypes().Where(a => a.Name == "HandlerType").FirstOrDefault();
                    //if (handlerType != null)
                    //{
                    //    // 建立工厂模式，便于实例化不同的工作流处理类
                    //    foreach (FieldInfo v in handlerType.GetFields())
                    //    {
                    //        string strName = v.GetValue(handlerType).ToString();
                    //        string strHandlerName = strName + "Handler";
                    //        Type handlerClass = Application.GetTypes().Where(a => a.Name == strHandlerName).FirstOrDefault();
                    //        if (handlerClass != null)
                    //        {
                    //            builder.RegisterType(handlerClass)
                    //                .Keyed<IWFHandler>(strName);
                    //        }
                    //    }
                    //}
                    //List<Type> listMethodClass = Application.GetTypes().Where(a => a.Name.EndsWith("WFMethods") && !a.IsInterface).ToList();
                    //listMethodClass.ForEach(methodClass =>
                    //{
                    //    var strClassName = methodClass.Name.Replace("WFMethods", "");

                    //    builder.RegisterType(methodClass)
                    //        .Keyed<IWFMethods>(strClassName);
                    //});
                    // 建立工厂模式，便于实例化不同的工作流处理类
                    //foreach (int v in Enum.GetValues(typeof(OAEnum)))
                    //{
                    //    string strEnumName = Enum.GetName(typeof(OAEnum), v);
                    //    string strHandlerName = strEnumName + "Handler";
                    //    Type handlerClass = Application.GetTypes().Where(a => a.Name == strHandlerName).FirstOrDefault();
                    //    if (handlerClass != null)
                    //    {
                    //        var _enum = (OAEnum)v;
                    //        builder.RegisterType(handlerClass)
                    //            .Keyed<IWFHandler>(_enum);
                    //    }
                    //}
                }
            }

            //////根据名称约定（服务层的接口和实现均以Services结尾），实现服务接口和服务实现的依赖
            ////builder.RegisterAssemblyTypes(SysApplication, SysApplication)
            ////  .Where(t => t.Name.EndsWith("AppService"))
            ////  .AsImplementedInterfaces();
            ////builder.RegisterAssemblyTypes(ZeroApplication, ZeroApplication)
            ////  .Where(t => t.Name.EndsWith("AppService"))
            ////  .AsImplementedInterfaces();

            //根据名称约定（数据访问层的接口和实现均以Repository结尾），实现数据访问接口和数据访问实现的依赖
            //builder.RegisterAssemblyTypes(iRepository, repository)
            //  .Where(t => t.Name.EndsWith("Repository"))
            //  .AsImplementedInterfaces();
        }
    }
}